const fs = require('fs')
const image = require('imageinfo')
const path = require('path')

function readFileList(path, filesList) {
  let files = fs.readdirSync(path)
  files.forEach(function (itm, index) {
    let stat = fs.statSync(path + itm)
    if (stat.isDirectory()) {
      readFileList(path + itm + "/", filesList)
    } else {
      let obj = {}
      obj.path = path
      obj.filename = itm
      filesList.push(obj)
    }
  })
}

let getFiles = {

  getFileList: function (path) {
    let filesList = []
    readFileList(path, filesList)
    return filesList
  },

  getImageFiles: function (path) {
    let imageList = []
    this.getFileList(path).forEach((item) => {
      let ms = image(fs.readFileSync(item.path + item.filename))
      ms.mimeType && (imageList.push(item.filename))
    })
    return imageList
  }

}

let getImageFiles = getFiles.getImageFiles("C:\\Users\\Administrator\\Desktop\\修改后图片\\").toString()
let FileListArr = getFiles.getFileList("C:\\Users\\Administrator\\Desktop\\将要被替换\\")
let ImageFilesArr = getImageFiles.split(',')

ImageFilesArr.forEach(value => {
  FileListArr.forEach(fvalue => {
    if (fvalue.filename == value) {
      // 图片移动有则覆盖
      let fileName = value
      let sourceFile = path.join('C:\\Users\\Administrator\\Desktop\\修改后图片\\', fileName)
      let destPath = path.join(fvalue.path, fileName)
      fs.rename(sourceFile, destPath, err => {
        if (err) throw err
        fs.stat(destPath, function (err, stats) {
          if (err) throw err
          console.log('stats: ' + JSON.stringify(stats))
        })
      })

    }
  })
})
